{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import google.generativeai as genai\n",
        "import json\n",
        "import time\n",
        "import re\n",
        "from typing import Dict, List, Any\n",
        "from datetime import datetime\n",
        "import traceback"
      ],
      "metadata": {
        "id": "coBU66cVnmNz"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class SelfImprovingAgent:\n",
        "    def __init__(self, api_key: str):\n",
        "        \"\"\"Initialize the self-improving agent with Gemini API\"\"\"\n",
        "        genai.configure(api_key=api_key)\n",
        "        self.model = genai.GenerativeModel('gemini-1.5-flash')\n",
        "\n",
        "        self.memory = {\n",
        "            'successful_strategies': [],\n",
        "            'failed_attempts': [],\n",
        "            'learned_patterns': [],\n",
        "            'performance_metrics': [],\n",
        "            'code_improvements': []\n",
        "        }\n",
        "\n",
        "        self.capabilities = {\n",
        "            'problem_solving': 0.5,\n",
        "            'code_generation': 0.5,\n",
        "            'learning_efficiency': 0.5,\n",
        "            'error_handling': 0.5\n",
        "        }\n",
        "\n",
        "        self.iteration_count = 0\n",
        "        self.improvement_history = []\n",
        "\n",
        "    def analyze_task(self, task: str) -> Dict[str, Any]:\n",
        "        \"\"\"Analyze a given task and determine approach\"\"\"\n",
        "        analysis_prompt = f\"\"\"\n",
        "        Analyze this task and provide a structured approach:\n",
        "        Task: {task}\n",
        "\n",
        "        Please provide:\n",
        "        1. Task complexity (1-10)\n",
        "        2. Required skills\n",
        "        3. Potential challenges\n",
        "        4. Recommended approach\n",
        "        5. Success criteria\n",
        "\n",
        "        Format as JSON.\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            response = self.model.generate_content(analysis_prompt)\n",
        "            json_match = re.search(r'\\{.*\\}', response.text, re.DOTALL)\n",
        "            if json_match:\n",
        "                return json.loads(json_match.group())\n",
        "            else:\n",
        "                return {\n",
        "                    \"complexity\": 5,\n",
        "                    \"skills\": [\"general problem solving\"],\n",
        "                    \"challenges\": [\"undefined requirements\"],\n",
        "                    \"approach\": \"iterative improvement\",\n",
        "                    \"success_criteria\": [\"task completion\"]\n",
        "                }\n",
        "        except Exception as e:\n",
        "            print(f\"Task analysis error: {e}\")\n",
        "            return {\"complexity\": 5, \"skills\": [], \"challenges\": [], \"approach\": \"basic\", \"success_criteria\": []}\n",
        "\n",
        "    def solve_problem(self, problem: str) -> Dict[str, Any]:\n",
        "        \"\"\"Attempt to solve a problem using current capabilities\"\"\"\n",
        "        self.iteration_count += 1\n",
        "        print(f\"\\n=== Iteration {self.iteration_count} ===\")\n",
        "        print(f\"Problem: {problem}\")\n",
        "\n",
        "        task_analysis = self.analyze_task(problem)\n",
        "        print(f\"Task Analysis: {task_analysis}\")\n",
        "\n",
        "        solution_prompt = f\"\"\"\n",
        "        Based on my previous learning and capabilities, solve this problem:\n",
        "        Problem: {problem}\n",
        "\n",
        "        My current capabilities: {self.capabilities}\n",
        "        Previous successful strategies: {self.memory['successful_strategies'][-3:]}  # Last 3\n",
        "        Known patterns: {self.memory['learned_patterns'][-3:]}  # Last 3\n",
        "\n",
        "        Provide a detailed solution with:\n",
        "        1. Step-by-step approach\n",
        "        2. Code implementation (if applicable)\n",
        "        3. Expected outcome\n",
        "        4. Potential improvements\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            start_time = time.time()\n",
        "            response = self.model.generate_content(solution_prompt)\n",
        "            solve_time = time.time() - start_time\n",
        "\n",
        "            solution = {\n",
        "                'problem': problem,\n",
        "                'solution': response.text,\n",
        "                'solve_time': solve_time,\n",
        "                'iteration': self.iteration_count,\n",
        "                'task_analysis': task_analysis\n",
        "            }\n",
        "\n",
        "            quality_score = self.evaluate_solution(solution)\n",
        "            solution['quality_score'] = quality_score\n",
        "\n",
        "            self.memory['performance_metrics'].append({\n",
        "                'iteration': self.iteration_count,\n",
        "                'quality': quality_score,\n",
        "                'time': solve_time,\n",
        "                'complexity': task_analysis.get('complexity', 5)\n",
        "            })\n",
        "\n",
        "            if quality_score > 0.7:\n",
        "                self.memory['successful_strategies'].append(solution)\n",
        "                print(f\"✅ Solution Quality: {quality_score:.2f} (Success)\")\n",
        "            else:\n",
        "                self.memory['failed_attempts'].append(solution)\n",
        "                print(f\"❌ Solution Quality: {quality_score:.2f} (Needs Improvement)\")\n",
        "\n",
        "            return solution\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"Problem solving error: {e}\")\n",
        "            error_solution = {\n",
        "                'problem': problem,\n",
        "                'solution': f\"Error occurred: {str(e)}\",\n",
        "                'solve_time': 0,\n",
        "                'iteration': self.iteration_count,\n",
        "                'quality_score': 0.0,\n",
        "                'error': str(e)\n",
        "            }\n",
        "            self.memory['failed_attempts'].append(error_solution)\n",
        "            return error_solution\n",
        "\n",
        "    def evaluate_solution(self, solution: Dict[str, Any]) -> float:\n",
        "        \"\"\"Evaluate the quality of a solution\"\"\"\n",
        "        evaluation_prompt = f\"\"\"\n",
        "        Evaluate this solution on a scale of 0.0 to 1.0:\n",
        "\n",
        "        Problem: {solution['problem']}\n",
        "        Solution: {solution['solution'][:500]}...  # Truncated for evaluation\n",
        "\n",
        "        Rate based on:\n",
        "        1. Completeness (addresses all aspects)\n",
        "        2. Correctness (logically sound)\n",
        "        3. Clarity (well explained)\n",
        "        4. Practicality (implementable)\n",
        "        5. Innovation (creative approach)\n",
        "\n",
        "        Respond with just a decimal number between 0.0 and 1.0.\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            response = self.model.generate_content(evaluation_prompt)\n",
        "            score_match = re.search(r'(\\d+\\.?\\d*)', response.text)\n",
        "            if score_match:\n",
        "                score = float(score_match.group(1))\n",
        "                return min(max(score, 0.0), 1.0)\n",
        "            return 0.5\n",
        "        except:\n",
        "            return 0.5\n",
        "\n",
        "    def learn_from_experience(self):\n",
        "        \"\"\"Analyze past performance and improve capabilities\"\"\"\n",
        "        print(\"\\n🧠 Learning from experience...\")\n",
        "\n",
        "        if len(self.memory['performance_metrics']) < 2:\n",
        "            return\n",
        "\n",
        "        learning_prompt = f\"\"\"\n",
        "        Analyze my performance and suggest improvements:\n",
        "\n",
        "        Recent Performance Metrics: {self.memory['performance_metrics'][-5:]}\n",
        "        Successful Strategies: {len(self.memory['successful_strategies'])}\n",
        "        Failed Attempts: {len(self.memory['failed_attempts'])}\n",
        "\n",
        "        Current Capabilities: {self.capabilities}\n",
        "\n",
        "        Provide:\n",
        "        1. Performance trends analysis\n",
        "        2. Identified weaknesses\n",
        "        3. Specific improvement suggestions\n",
        "        4. New capability scores (0.0-1.0 for each capability)\n",
        "        5. New patterns learned\n",
        "\n",
        "        Format as JSON with keys: analysis, weaknesses, improvements, new_capabilities, patterns\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            response = self.model.generate_content(learning_prompt)\n",
        "\n",
        "            json_match = re.search(r'\\{.*\\}', response.text, re.DOTALL)\n",
        "            if json_match:\n",
        "                learning_results = json.loads(json_match.group())\n",
        "\n",
        "                if 'new_capabilities' in learning_results:\n",
        "                    old_capabilities = self.capabilities.copy()\n",
        "                    for capability, score in learning_results['new_capabilities'].items():\n",
        "                        if capability in self.capabilities:\n",
        "                            self.capabilities[capability] = min(max(float(score), 0.0), 1.0)\n",
        "\n",
        "                    print(f\"📈 Capability Updates:\")\n",
        "                    for cap, (old, new) in zip(self.capabilities.keys(),\n",
        "                                             zip(old_capabilities.values(), self.capabilities.values())):\n",
        "                        change = new - old\n",
        "                        print(f\"  {cap}: {old:.2f} → {new:.2f} ({change:+.2f})\")\n",
        "\n",
        "                if 'patterns' in learning_results:\n",
        "                    self.memory['learned_patterns'].extend(learning_results['patterns'])\n",
        "\n",
        "                self.improvement_history.append({\n",
        "                    'iteration': self.iteration_count,\n",
        "                    'timestamp': datetime.now().isoformat(),\n",
        "                    'learning_results': learning_results,\n",
        "                    'capabilities_before': old_capabilities,\n",
        "                    'capabilities_after': self.capabilities.copy()\n",
        "                })\n",
        "\n",
        "                print(f\"✨ Learned {len(learning_results.get('patterns', []))} new patterns\")\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"Learning error: {e}\")\n",
        "\n",
        "    def generate_improved_code(self, current_code: str, improvement_goal: str) -> str:\n",
        "        \"\"\"Generate improved version of code\"\"\"\n",
        "        improvement_prompt = f\"\"\"\n",
        "        Improve this code based on the goal:\n",
        "\n",
        "        Current Code:\n",
        "        {current_code}\n",
        "\n",
        "        Improvement Goal: {improvement_goal}\n",
        "        My current capabilities: {self.capabilities}\n",
        "        Learned patterns: {self.memory['learned_patterns'][-3:]}\n",
        "\n",
        "        Provide improved code with:\n",
        "        1. Enhanced functionality\n",
        "        2. Better error handling\n",
        "        3. Improved efficiency\n",
        "        4. Clear comments explaining improvements\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            response = self.model.generate_content(improvement_prompt)\n",
        "\n",
        "            improved_code = {\n",
        "                'original': current_code,\n",
        "                'improved': response.text,\n",
        "                'goal': improvement_goal,\n",
        "                'iteration': self.iteration_count\n",
        "            }\n",
        "\n",
        "            self.memory['code_improvements'].append(improved_code)\n",
        "            return response.text\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"Code improvement error: {e}\")\n",
        "            return current_code\n",
        "\n",
        "    def self_modify(self):\n",
        "        \"\"\"Attempt to improve the agent's own code\"\"\"\n",
        "        print(\"\\n🔧 Attempting self-modification...\")\n",
        "\n",
        "        current_method = \"\"\"\n",
        "        def solve_problem(self, problem: str) -> Dict[str, Any]:\n",
        "            # Current implementation\n",
        "            pass\n",
        "        \"\"\"\n",
        "\n",
        "        improved_method = self.generate_improved_code(\n",
        "            current_method,\n",
        "            \"Make problem solving more efficient and accurate\"\n",
        "        )\n",
        "\n",
        "        print(\"Generated improved method structure\")\n",
        "        print(\"Note: Actual self-modification requires careful implementation in production\")\n",
        "\n",
        "    def run_improvement_cycle(self, problems: List[str], cycles: int = 3):\n",
        "        \"\"\"Run a complete improvement cycle\"\"\"\n",
        "        print(f\"🚀 Starting {cycles} improvement cycles with {len(problems)} problems\")\n",
        "\n",
        "        for cycle in range(cycles):\n",
        "            print(f\"\\n{'='*50}\")\n",
        "            print(f\"IMPROVEMENT CYCLE {cycle + 1}/{cycles}\")\n",
        "            print(f\"{'='*50}\")\n",
        "\n",
        "            cycle_results = []\n",
        "            for problem in problems:\n",
        "                result = self.solve_problem(problem)\n",
        "                cycle_results.append(result)\n",
        "                time.sleep(1)\n",
        "\n",
        "            self.learn_from_experience()\n",
        "\n",
        "            if cycle < cycles - 1:\n",
        "                self.self_modify()\n",
        "\n",
        "            avg_quality = sum(r.get('quality_score', 0) for r in cycle_results) / len(cycle_results)\n",
        "            print(f\"\\n📊 Cycle {cycle + 1} Summary:\")\n",
        "            print(f\"  Average Solution Quality: {avg_quality:.2f}\")\n",
        "            print(f\"  Current Capabilities: {self.capabilities}\")\n",
        "            print(f\"  Total Patterns Learned: {len(self.memory['learned_patterns'])}\")\n",
        "\n",
        "            time.sleep(2)\n",
        "\n",
        "    def get_performance_report(self) -> str:\n",
        "        \"\"\"Generate a comprehensive performance report\"\"\"\n",
        "        if not self.memory['performance_metrics']:\n",
        "            return \"No performance data available yet.\"\n",
        "\n",
        "        metrics = self.memory['performance_metrics']\n",
        "        avg_quality = sum(m['quality'] for m in metrics) / len(metrics)\n",
        "        avg_time = sum(m['time'] for m in metrics) / len(metrics)\n",
        "\n",
        "        report = f\"\"\"\n",
        "        📈 AGENT PERFORMANCE REPORT\n",
        "        {'='*40}\n",
        "\n",
        "        Total Iterations: {self.iteration_count}\n",
        "        Average Solution Quality: {avg_quality:.3f}\n",
        "        Average Solve Time: {avg_time:.2f}s\n",
        "\n",
        "        Successful Solutions: {len(self.memory['successful_strategies'])}\n",
        "        Failed Attempts: {len(self.memory['failed_attempts'])}\n",
        "        Success Rate: {len(self.memory['successful_strategies']) / max(1, self.iteration_count) * 100:.1f}%\n",
        "\n",
        "        Current Capabilities:\n",
        "        {json.dumps(self.capabilities, indent=2)}\n",
        "\n",
        "        Patterns Learned: {len(self.memory['learned_patterns'])}\n",
        "        Code Improvements: {len(self.memory['code_improvements'])}\n",
        "        \"\"\"\n",
        "\n",
        "        return report"
      ],
      "metadata": {
        "id": "dVXGjunxnq7X"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def main():\n",
        "    \"\"\"Main function to demonstrate the self-improving agent\"\"\"\n",
        "\n",
        "    API_KEY = \"Use Your GEMINI KEY Here\"\n",
        "\n",
        "    if API_KEY == \"Use Your GEMINI KEY Here\":\n",
        "        print(\"⚠️  Please set your Gemini API key in the API_KEY variable\")\n",
        "        print(\"Get your API key from: https://makersuite.google.com/app/apikey\")\n",
        "        return\n",
        "\n",
        "    agent = SelfImprovingAgent(API_KEY)\n",
        "\n",
        "    test_problems = [\n",
        "        \"Write a function to calculate the factorial of a number\",\n",
        "        \"Create a simple text-based calculator that handles basic operations\",\n",
        "        \"Design a system to find the shortest path between two points in a graph\",\n",
        "        \"Implement a basic recommendation system for movies based on user preferences\",\n",
        "        \"Create a machine learning model to predict house prices based on features\"\n",
        "    ]\n",
        "\n",
        "    print(\"🤖 Self-Improving Agent Demo\")\n",
        "    print(\"This agent will attempt to solve problems and improve over time\")\n",
        "\n",
        "    agent.run_improvement_cycle(test_problems, cycles=3)\n",
        "\n",
        "    print(\"\\n\" + agent.get_performance_report())\n",
        "\n",
        "    print(\"\\n\" + \"=\"*50)\n",
        "    print(\"TESTING IMPROVED AGENT\")\n",
        "    print(\"=\"*50)\n",
        "\n",
        "    final_problem = \"Create an efficient algorithm to sort a large dataset\"\n",
        "    final_result = agent.solve_problem(final_problem)\n",
        "\n",
        "    print(f\"\\nFinal Problem Solution Quality: {final_result.get('quality_score', 0):.2f}\")"
      ],
      "metadata": {
        "id": "G2F5FNf7oDuA"
      },
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "_Gie6947mKoV",
        "outputId": "7b330208-1613-4b5a-a2b8-340af13b16e6"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "    📋 SETUP INSTRUCTIONS FOR GOOGLE COLAB:\n",
            "    \n",
            "    1. Install the Gemini API client:\n",
            "       !pip install google-generativeai\n",
            "    \n",
            "    2. Get your Gemini API key:\n",
            "       - Go to https://makersuite.google.com/app/apikey\n",
            "       - Create a new API key\n",
            "       - Copy the key\n",
            "    \n",
            "    3. Replace 'your-gemini-api-key-here' with your actual API key\n",
            "    \n",
            "    4. Run the code!\n",
            "    \n",
            "    🔧 CUSTOMIZATION OPTIONS:\n",
            "    - Modify test_problems list to add your own challenges\n",
            "    - Adjust improvement cycles count\n",
            "    - Add new capabilities to track\n",
            "    - Extend the learning mechanisms\n",
            "    \n",
            "    💡 IMPROVEMENT IDEAS:\n",
            "    - Add persistent memory (save/load agent state)\n",
            "    - Implement more sophisticated evaluation metrics\n",
            "    - Add domain-specific problem types\n",
            "    - Create visualization of improvement over time\n",
            "    \n",
            "\n",
            "============================================================\n",
            "🤖 Self-Improving Agent Demo\n",
            "This agent will attempt to solve problems and improve over time\n",
            "🚀 Starting 3 improvement cycles with 5 problems\n",
            "\n",
            "==================================================\n",
            "IMPROVEMENT CYCLE 1/3\n",
            "==================================================\n",
            "\n",
            "=== Iteration 1 ===\n",
            "Problem: Write a function to calculate the factorial of a number\n",
            "Task Analysis: {'task': 'Write a function to calculate the factorial of a number', 'analysis': {'complexity': 2, 'required_skills': ['Basic programming knowledge', 'Understanding of loops (iterative approach) or recursion (recursive approach)', 'Handling of edge cases (e.g., factorial of 0 or negative numbers)'], 'potential_challenges': ['Handling large numbers (potential overflow for iterative approach)', 'Understanding and implementing recursion correctly (recursive approach)', 'Efficiently handling edge cases (e.g., factorial of 0, negative numbers)', 'Choosing the appropriate algorithm (iterative vs. recursive)'], 'recommended_approach': {'step1': 'Define the function signature:  `factorial(n)` where `n` is the input number.', 'step2': 'Handle edge cases:  If `n` is 0, return 1. If `n` is negative, raise an error or return an appropriate value (e.g., -1 or None).', 'step3': 'Choose an algorithm: \\n* **Iterative approach:** Use a loop to multiply numbers from 1 to `n`. This is generally more efficient for large numbers and avoids potential stack overflow issues.\\n* **Recursive approach:** Define the function recursively using the formula: factorial(n) = n * factorial(n-1). This is more elegant but can be less efficient and prone to stack overflow for very large numbers.', 'step4': 'Implement the chosen algorithm.', 'step5': 'Test the function with various inputs, including edge cases (0, negative numbers, positive integers).', 'step6': 'Consider adding error handling for non-integer inputs.'}, 'success_criteria': ['The function correctly calculates the factorial for positive integers.', 'The function handles the edge case of 0 (factorial of 0 is 1).', 'The function handles negative inputs gracefully (e.g., raises an error or returns a specific value).', 'The function is well-documented with clear comments.', 'The function is reasonably efficient (especially for larger input values).', 'The code is well-structured and readable.']}}\n",
            "❌ Solution Quality: 0.20 (Needs Improvement)\n",
            "\n",
            "=== Iteration 2 ===\n",
            "Problem: Create a simple text-based calculator that handles basic operations\n",
            "Task Analysis: {'task': 'Create a simple text-based calculator that handles basic operations', 'analysis': {'complexity': 3, 'requiredSkills': ['Basic programming knowledge (e.g., variables, data types, operators, input/output)', 'Understanding of control flow (if-else statements)', 'Ability to handle user input', 'Basic error handling (e.g., handling invalid input)'], 'potentialChallenges': ['Handling invalid input (e.g., non-numeric input, division by zero)', 'Implementing robust error messages', 'Designing a user-friendly interface (though simple, it should be intuitive)', 'Choosing the right programming language and libraries (if any)', 'Testing the calculator with various inputs to ensure accuracy'], 'recommendedApproach': ['1. **Choose a programming language:**  Python is a good choice for beginners due to its readability and ease of use.', '2. **Design the user interface:**  Decide how the user will interact with the calculator (e.g., prompt for numbers and operator).', '3. **Implement input handling:**  Write code to get numerical input from the user and handle potential errors (e.g., non-numeric input).', '4. **Implement basic arithmetic operations:** Write functions or use operators to perform addition, subtraction, multiplication, and division.', '5. **Implement error handling:** Add checks for division by zero and other potential errors, providing informative error messages.', '6. **Test thoroughly:** Test the calculator with a variety of inputs, including edge cases and invalid inputs.', '7. **(Optional) Enhancements:** Consider adding features like more advanced operations (e.g., exponentiation, modulo), operator precedence, or a more sophisticated interface.'], 'successCriteria': ['The calculator correctly performs addition, subtraction, multiplication, and division.', 'The calculator handles invalid input gracefully (e.g., displays error messages and does not crash).', \"The calculator's output is clear and easy to understand.\", 'The code is well-structured, readable, and easy to maintain.', 'The calculator passes a series of test cases covering various scenarios, including edge cases (e.g., division by zero).']}}\n",
            "❌ Solution Quality: 0.70 (Needs Improvement)\n",
            "\n",
            "=== Iteration 3 ===\n",
            "Problem: Design a system to find the shortest path between two points in a graph\n",
            "Task Analysis: {'task': 'Design a system to find the shortest path between two points in a graph', 'analysis': {'complexity': 7, 'requiredSkills': ['Algorithm design and analysis', 'Data structures (graphs, priority queues)', 'Software design principles', 'Problem-solving skills', 'Coding skills (in a suitable language like Python, Java, C++)', 'Testing and debugging', 'Understanding of graph theory concepts (weighted graphs, directed/undirected graphs)'], 'potentialChallenges': ['Handling large graphs (memory and computation time)', 'Dealing with different types of graphs (weighted, unweighted, directed, undirected)', 'Choosing the most efficient algorithm for the specific graph type and size', 'Handling negative edge weights (Bellman-Ford algorithm might be needed)', 'Dealing with cycles in the graph', 'Implementing efficient data structures for optimal performance', 'Error handling and input validation', 'Integration with existing systems (if applicable)'], 'recommendedApproach': {'steps': ['1. **Problem Definition:** Clearly define the input (graph representation, start and end nodes) and output (shortest path). Specify the type of graph (weighted, directed etc.)', \"2. **Algorithm Selection:** Choose an appropriate shortest path algorithm based on the graph characteristics.  Dijkstra's algorithm is suitable for non-negative weighted graphs. Bellman-Ford can handle negative edge weights but is slower. A* search can be more efficient for large graphs with heuristics.\", \"3. **Data Structure Design:** Select suitable data structures to represent the graph (adjacency matrix or adjacency list) and to implement the chosen algorithm (priority queue for Dijkstra's).\", '4. **Algorithm Implementation:** Implement the selected algorithm using the chosen data structures. Write clean, well-documented code.', '5. **Testing and Validation:** Thoroughly test the system with various test cases, including edge cases and large graphs, to ensure correctness and performance.', '6. **Optimization (optional):**  Explore optimizations like heuristics (A*), parallel processing, or graph preprocessing techniques to improve performance for large graphs.', \"7. **Documentation:** Document the system's design, implementation, and usage.\"], 'algorithmConsiderations': {\"Dijkstra's Algorithm\": 'Suitable for non-negative weighted graphs. Efficient and widely used.', 'Bellman-Ford Algorithm': \"Handles negative edge weights but is slower than Dijkstra's.\", 'A* Search Algorithm': 'Efficient for large graphs if a good heuristic is available.'}}, 'successCriteria': ['The system correctly finds the shortest path between any two points in the given graph.', 'The system is efficient in terms of time and space complexity, especially for large graphs.', 'The system is robust and handles various input scenarios (including invalid inputs) gracefully.', 'The system is well-documented and easy to understand and maintain.']}}\n",
            "❌ Solution Quality: 0.70 (Needs Improvement)\n",
            "\n",
            "=== Iteration 4 ===\n",
            "Problem: Implement a basic recommendation system for movies based on user preferences\n",
            "Task analysis error: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))\n",
            "Task Analysis: {'complexity': 5, 'skills': [], 'challenges': [], 'approach': 'basic', 'success_criteria': []}\n",
            "❌ Solution Quality: 0.60 (Needs Improvement)\n",
            "\n",
            "=== Iteration 5 ===\n",
            "Problem: Create a machine learning model to predict house prices based on features\n",
            "Task Analysis: {'task': 'Create a machine learning model to predict house prices based on features', 'analysis': {'complexity': 7, 'required_skills': ['Data cleaning and preprocessing (handling missing values, outliers, feature scaling)', 'Feature engineering (creating new features from existing ones)', 'Exploratory data analysis (EDA) to understand data distribution and relationships', 'Model selection (choosing appropriate regression algorithms)', 'Model training and evaluation (using appropriate metrics like RMSE, MAE, R-squared)', 'Hyperparameter tuning (optimizing model performance)', 'Model deployment (depending on the context)', 'Programming skills (Python or R are common choices)', 'Familiarity with machine learning libraries (e.g., scikit-learn, TensorFlow, PyTorch)'], 'potential_challenges': ['Data quality issues (missing data, inconsistent data formats, outliers)', 'Feature selection (identifying the most relevant features)', 'Handling non-linear relationships between features and price', 'Overfitting (model performs well on training data but poorly on unseen data)', 'Underfitting (model is too simple to capture the complexity of the data)', 'Dealing with high dimensionality (many features)', 'Interpreting model results and explaining predictions', 'Finding a suitable dataset (sufficient size and relevant features)', 'Computational resources for training complex models'], 'recommended_approach': ['1. **Data Acquisition and Exploration:** Gather a relevant dataset and perform EDA to understand its characteristics. Visualize data distributions and correlations.', '2. **Data Preprocessing:** Clean the data, handle missing values (imputation or removal), and convert categorical features into numerical representations (one-hot encoding, label encoding). Scale numerical features.', '3. **Feature Engineering:** Create new features that might improve model performance (e.g., combining features, creating interaction terms, calculating area ratios).', '4. **Model Selection:** Choose appropriate regression models (Linear Regression, Ridge Regression, Lasso Regression, Random Forest, Gradient Boosting, Neural Networks). Consider the complexity of the data and potential overfitting/underfitting.', '5. **Model Training and Evaluation:** Split data into training, validation, and testing sets. Train the selected model on the training set, tune hyperparameters using the validation set, and evaluate performance on the testing set using metrics like RMSE, MAE, R-squared.', '6. **Model Selection and Fine-tuning:** Compare the performance of different models and choose the best performing one.  Further refine the chosen model through hyperparameter tuning and feature engineering.', '7. **Deployment (Optional):** Deploy the model using suitable methods depending on the need (e.g., web application, API).'], 'success_criteria': ['Achieving a low RMSE (Root Mean Squared Error) and MAE (Mean Absolute Error) on the testing set.', 'Achieving a high R-squared value on the testing set.', 'The model should generalize well to unseen data (avoid overfitting).', 'The model should be interpretable to some degree (depending on the chosen model)', 'The model should be robust to outliers and noise.']}}\n",
            "❌ Solution Quality: 0.60 (Needs Improvement)\n",
            "\n",
            "🧠 Learning from experience...\n",
            "📈 Capability Updates:\n",
            "  problem_solving: 0.50 → 0.30 (-0.20)\n",
            "  code_generation: 0.50 → 0.50 (+0.00)\n",
            "  learning_efficiency: 0.50 → 0.20 (-0.30)\n",
            "  error_handling: 0.50 → 0.30 (-0.20)\n",
            "✨ Learned 3 new patterns\n",
            "\n",
            "🔧 Attempting self-modification...\n",
            "Generated improved method structure\n",
            "Note: Actual self-modification requires careful implementation in production\n",
            "\n",
            "📊 Cycle 1 Summary:\n",
            "  Average Solution Quality: 0.56\n",
            "  Current Capabilities: {'problem_solving': 0.3, 'code_generation': 0.5, 'learning_efficiency': 0.2, 'error_handling': 0.3}\n",
            "  Total Patterns Learned: 3\n",
            "\n",
            "==================================================\n",
            "IMPROVEMENT CYCLE 2/3\n",
            "==================================================\n",
            "\n",
            "=== Iteration 6 ===\n",
            "Problem: Write a function to calculate the factorial of a number\n",
            "Task Analysis: {'task': 'Write a function to calculate the factorial of a number', 'analysis': {'complexity': 2, 'required_skills': ['Basic programming knowledge', 'Understanding of loops (iterative approach) or recursion (recursive approach)', 'Ability to handle data types (integers)', 'Basic error handling (e.g., handling negative input)'], 'potential_challenges': ['Handling negative input (factorials are not defined for negative numbers)', 'Handling large numbers (factorial grows very quickly, leading to potential overflow issues)', 'Choosing between iterative and recursive approaches (each has trade-offs in terms of readability, efficiency, and risk of stack overflow for recursion)', 'Efficient handling of zero factorial (which is 1)'], 'recommended_approach': {'steps': ['Define the function signature (input: integer, output: integer)', 'Handle the base case: factorial of 0 is 1', 'Handle negative input: return an error message or throw an exception', 'Choose an approach: iterative (generally preferred for efficiency and avoids stack overflow) or recursive (more elegant but can be less efficient and prone to stack overflow for large numbers)', 'Implement the chosen approach: iterative approach uses a loop; recursive approach uses a function calling itself.', 'Test thoroughly with various inputs, including 0, positive integers, and negative integers', 'Consider adding error handling to manage potential overflow for extremely large numbers (e.g., using a library for arbitrary-precision arithmetic if necessary).'], 'iterative_example': 'function factorialIterative(n) {\\n  if (n < 0) return -1; //Error for negative input \\n  if (n === 0) return 1;\\n  let result = 1;\\n  for (let i = 1; i <= n; i++) {\\n    result *= i;\\n  }\\n  return result;\\n}', 'recursive_example': 'function factorialRecursive(n) {\\n  if (n < 0) return -1; //Error for negative input\\n  if (n === 0) return 1;\\n  return n * factorialRecursive(n - 1);\\n}'}, 'success_criteria': ['The function correctly calculates the factorial for non-negative integers.', 'The function handles negative input gracefully (either returns an error or throws an exception).', 'The function is well-documented and readable.', 'The function is efficient for reasonably sized inputs (no noticeable performance issues).', 'The function includes appropriate error handling to prevent crashes or unexpected results']}}\n",
            "❌ Solution Quality: 0.20 (Needs Improvement)\n",
            "\n",
            "=== Iteration 7 ===\n",
            "Problem: Create a simple text-based calculator that handles basic operations\n",
            "Task Analysis: {'task': 'Create a simple text-based calculator that handles basic operations', 'analysis': {'complexity': 3, 'required_skills': ['Basic programming knowledge (e.g., loops, conditional statements)', 'Input/output handling (getting user input and displaying output)', 'String manipulation (potentially for handling user input)', 'Basic arithmetic operations (+, -, *, /)', 'Error handling (e.g., handling division by zero)'], 'potential_challenges': ['Handling invalid user input (e.g., non-numeric input)', 'Implementing robust error handling (e.g., division by zero, incorrect format)', 'Designing a user-friendly interface (making it easy to use and understand)', 'Choosing an appropriate programming language and managing its libraries', 'Testing the calculator thoroughly to ensure accuracy'], 'recommended_approach': ['1. **Choose a programming language:** Select a language you are comfortable with (Python, JavaScript, C++, etc.).', '2. **Design the user interface:** Decide how the user will interact with the calculator (e.g., prompt for numbers and operator).', '3. **Implement input handling:**  Write code to get numerical inputs from the user and validate the inputs.', '4. **Implement arithmetic operations:** Write functions to perform addition, subtraction, multiplication, and division.', '5. **Implement error handling:**  Handle potential errors, like division by zero or non-numeric input, gracefully.', '6. **Implement output:** Display the results to the user in a clear and understandable format.', '7. **Test thoroughly:** Test with various inputs, including edge cases (e.g., large numbers, zero, negative numbers).', '8. (Optional) Enhancements: Consider adding features like operator precedence, memory functions, or more advanced operations.'], 'success_criteria': ['The calculator correctly performs basic arithmetic operations (+, -, *, /).', 'The calculator handles invalid input gracefully (e.g., displays an error message).', 'The calculator handles division by zero without crashing.', \"The calculator's output is clear and easy to understand.\", 'The code is well-structured, readable, and commented.']}}\n",
            "❌ Solution Quality: 0.40 (Needs Improvement)\n",
            "\n",
            "=== Iteration 8 ===\n",
            "Problem: Design a system to find the shortest path between two points in a graph\n",
            "Task Analysis: {'task': 'Design a system to find the shortest path between two points in a graph', 'analysis': {'complexity': 6, 'required_skills': ['Algorithm design and analysis (graph algorithms)', 'Data structures (graphs, priority queues)', 'Software design principles (modular design, object-oriented programming)', 'Programming skills (in a language suitable for algorithm implementation, e.g., Python, Java, C++)', 'Testing and debugging skills', 'Problem-solving skills'], 'potential_challenges': ['Handling large graphs efficiently (memory and computation)', 'Dealing with weighted edges (different costs associated with edges)', 'Addressing negative edge weights (which can lead to issues with some algorithms)', 'Handling cycles in the graph', 'Choosing the appropriate algorithm for different graph characteristics (dense vs. sparse, directed vs. undirected)', 'Implementing efficient data structures for graph representation (adjacency matrix vs. adjacency list)', 'Ensuring robustness and handling edge cases (e.g., disconnected graphs, invalid input)', 'Optimizing for performance (especially for real-time applications)', 'Choosing an appropriate data serialization/deserialization method to handle graph data'], 'recommended_approach': ['1. **Requirements Gathering:**  Clearly define the characteristics of the graph (weighted/unweighted, directed/undirected, size).', \"2. **Algorithm Selection:** Choose an appropriate shortest path algorithm based on the graph characteristics.  Consider Dijkstra's algorithm (for weighted, non-negative graphs), Bellman-Ford algorithm (for weighted graphs with potential negative edges), or A* search (for heuristic-informed search).\", '3. **Data Structure Selection:** Select a suitable data structure for representing the graph (adjacency matrix or adjacency list). Consider memory usage and performance implications.', '4. **Implementation:** Implement the chosen algorithm using a suitable programming language.', '5. **Testing and Validation:** Thoroughly test the system with various input graphs, including edge cases and large graphs, to ensure correctness and efficiency.', '6. **Optimization (Optional):**  If performance is critical, explore optimizations such as using heuristics or more efficient data structures.'], 'success_criteria': ['The system correctly identifies the shortest path between any two given nodes in the graph.', 'The system handles various graph types (weighted/unweighted, directed/undirected).', 'The system performs efficiently, especially for large graphs.', 'The system is robust and handles edge cases gracefully.', 'The system is well-documented and easy to understand.', 'The system meets performance benchmarks (if any are defined).']}}\n",
            "❌ Solution Quality: 0.70 (Needs Improvement)\n",
            "\n",
            "=== Iteration 9 ===\n",
            "Problem: Implement a basic recommendation system for movies based on user preferences\n",
            "Task Analysis: {'task': 'Implement a basic movie recommendation system based on user preferences', 'analysis': {'complexity': 6, 'required_skills': ['Programming (Python preferred)', 'Data manipulation and cleaning (using Pandas or similar)', 'Basic statistics and data analysis', 'Familiarity with recommendation algorithms (e.g., collaborative filtering, content-based filtering)', 'Data structures and algorithms', 'Database management (optional, depending on data storage)', 'Model evaluation and selection'], 'potential_challenges': ['Data sparsity (not enough user ratings)', 'Cold start problem (new users or movies with few ratings)', 'Data quality issues (inconsistent or missing data)', 'Scalability (handling large datasets)', 'Algorithm selection (choosing the right algorithm for the data)', 'Evaluating the recommendation quality (defining appropriate metrics)', 'Overfitting (model performs well on training data but poorly on new data)'], 'recommended_approach': {'steps': ['1. **Data Acquisition and Preparation:** Gather movie data (titles, genres, etc.) and user ratings. Clean and preprocess the data, handling missing values and inconsistencies.', '2. **Feature Engineering:** Extract relevant features from the data.  For content-based filtering, this might include genre, actors, directors. For collaborative filtering, you need user-item interaction data (ratings).', '3. **Algorithm Selection:** Choose a suitable recommendation algorithm. For a basic system, consider starting with a simple collaborative filtering (user-based or item-based) or content-based filtering algorithm.  Consider hybrid approaches for better performance.', '4. **Model Training and Evaluation:** Train the chosen algorithm on the prepared data. Evaluate its performance using metrics like precision, recall, F1-score, RMSE, or NDCG.', '5. **System Implementation:** Integrate the trained model into a system that can take user preferences as input and generate movie recommendations. This could be a simple command-line interface or a web application.', '6. **Deployment and Monitoring:** Deploy the system and monitor its performance.  Continuously improve the system based on user feedback and performance metrics.'], 'algorithm_suggestions': ['Collaborative Filtering (User-based or Item-based)', 'Content-Based Filtering', 'Hybrid approaches (combining collaborative and content-based)'], 'evaluation_metrics': ['Precision', 'Recall', 'F1-score', 'RMSE (Root Mean Squared Error)', 'NDCG (Normalized Discounted Cumulative Gain)']}, 'success_criteria': ['The system generates relevant movie recommendations based on user preferences.', 'The system is able to handle a reasonable amount of data.', \"The system's recommendations are evaluated using appropriate metrics and meet acceptable performance thresholds (e.g., precision above a certain level).\", 'The system is robust and handles missing data and unexpected inputs gracefully.', 'The system is documented and easy to understand and maintain.']}}\n",
            "❌ Solution Quality: 0.60 (Needs Improvement)\n",
            "\n",
            "=== Iteration 10 ===\n",
            "Problem: Create a machine learning model to predict house prices based on features\n",
            "Task Analysis: {'task': 'Create a machine learning model to predict house prices based on features', 'analysis': {'complexity': 7, 'required_skills': ['Data cleaning and preprocessing (handling missing values, outliers, feature scaling)', 'Feature engineering (creating new features from existing ones)', 'Exploratory data analysis (EDA) to understand data distributions and relationships', 'Model selection (choosing appropriate regression algorithms like Linear Regression, Ridge Regression, Lasso Regression, Random Forest, Gradient Boosting, etc.)', 'Model training and evaluation (using metrics like RMSE, MAE, R-squared)', 'Hyperparameter tuning (optimizing model performance)', 'Model deployment (optional, depending on the project scope)', 'Programming skills (Python with libraries like Pandas, NumPy, Scikit-learn)', 'Data visualization (using libraries like Matplotlib, Seaborn)'], 'potential_challenges': ['Data quality issues (missing values, inconsistencies, outliers)', 'High dimensionality of features (curse of dimensionality)', 'Non-linear relationships between features and house prices', 'Overfitting or underfitting the model', 'Interpretability of the model (understanding which features are most important)', 'Handling categorical features (one-hot encoding, label encoding)', 'Selection of appropriate evaluation metrics', 'Data imbalance (if certain price ranges are under-represented)'], 'recommended_approach': ['1. **Data Acquisition and Exploration:** Gather the dataset, explore the data using EDA, visualize relationships between features and target variable (price). Identify missing values and outliers.', '2. **Data Preprocessing:** Clean the data by handling missing values (imputation or removal), addressing outliers (transformation or removal), and performing feature scaling (standardization or normalization). Encode categorical features.', '3. **Feature Engineering:** Create new features if necessary to improve model performance (e.g., combining features, creating interaction terms).', '4. **Model Selection:** Choose appropriate regression models based on data characteristics and project requirements. Start with simpler models (Linear Regression) and progress to more complex ones (Random Forest, Gradient Boosting) if necessary.', '5. **Model Training and Evaluation:** Split the data into training and testing sets. Train the selected model(s) on the training set and evaluate its performance on the testing set using appropriate metrics (RMSE, MAE, R-squared). Perform hyperparameter tuning to optimize performance.', '6. **Model Selection and Refinement:** Based on the evaluation metrics, select the best-performing model.  Iteratively refine the model by adjusting parameters, adding/removing features, or trying different algorithms.', '7. **Deployment (Optional):** Deploy the model to a production environment (e.g., web application, API) if required.'], 'success_criteria': ['Achieve a satisfactory level of accuracy in predicting house prices (e.g., low RMSE, high R-squared).', 'Develop a robust and generalizable model that performs well on unseen data.', 'Clearly document the entire process, including data preprocessing, model selection, and evaluation results.', 'The model is interpretable, allowing for understanding of the factors influencing house prices.']}}\n",
            "❌ Solution Quality: 0.60 (Needs Improvement)\n",
            "\n",
            "🧠 Learning from experience...\n",
            "📈 Capability Updates:\n",
            "  problem_solving: 0.30 → 0.40 (+0.10)\n",
            "  code_generation: 0.50 → 0.60 (+0.10)\n",
            "  learning_efficiency: 0.20 → 0.30 (+0.10)\n",
            "  error_handling: 0.30 → 0.50 (+0.20)\n",
            "✨ Learned 3 new patterns\n",
            "\n",
            "🔧 Attempting self-modification...\n",
            "Generated improved method structure\n",
            "Note: Actual self-modification requires careful implementation in production\n",
            "\n",
            "📊 Cycle 2 Summary:\n",
            "  Average Solution Quality: 0.50\n",
            "  Current Capabilities: {'problem_solving': 0.4, 'code_generation': 0.6, 'learning_efficiency': 0.3, 'error_handling': 0.5}\n",
            "  Total Patterns Learned: 6\n",
            "\n",
            "==================================================\n",
            "IMPROVEMENT CYCLE 3/3\n",
            "==================================================\n",
            "\n",
            "=== Iteration 11 ===\n",
            "Problem: Write a function to calculate the factorial of a number\n",
            "Task Analysis: {'task': 'Write a function to calculate the factorial of a number', 'analysis': {'complexity': 2, 'requiredSkills': ['Basic programming knowledge', 'Understanding of loops (iterative approach) or recursion (recursive approach)', 'Ability to handle edge cases (e.g., factorial of 0 or negative numbers)', 'Basic understanding of data types (integers)'], 'potentialChallenges': ['Handling edge cases (factorial of 0 is 1, factorial of negative numbers is undefined)', 'Dealing with potential overflow for large numbers (factorial grows rapidly)', 'Choosing between iterative and recursive approaches (each has trade-offs)', 'Error handling (e.g., for invalid input types)'], 'recommendedApproach': {'steps': ['Define the function signature (input: integer, output: integer)', 'Handle edge cases (factorial of 0 is 1, handle negative numbers appropriately - e.g., raise an exception or return an error code)', 'Implement the factorial calculation using either an iterative or recursive approach.', 'Iterative approach (recommended for larger numbers due to efficiency): use a loop to multiply numbers from 1 to n.', 'Recursive approach: define a base case (n=0 or n=1), and a recursive step (n! = n * (n-1)!).', 'Test thoroughly with various inputs, including edge cases and a range of positive integers.', 'Consider adding input validation to ensure the input is an integer.'], 'algorithm': 'Choose either iterative or recursive.  Iterative is generally preferred for its efficiency in avoiding stack overflow issues with large inputs.', 'example (iterative):': '```python\\ndef factorial_iterative(n):\\n  if n < 0:\\n    raise ValueError(\"Factorial is not defined for negative numbers.\")\\n  elif n == 0:\\n    return 1\\n  else:\\n    result = 1\\n    for i in range(1, n + 1):\\n      result *= i\\n    return result\\n```', 'example (recursive):': '```python\\ndef factorial_recursive(n):\\n  if n < 0:\\n    raise ValueError(\"Factorial is not defined for negative numbers.\")\\n  elif n == 0 or n == 1:\\n    return 1\\n  else:\\n    return n * factorial_recursive(n - 1)\\n```'}, 'successCriteria': ['The function correctly calculates the factorial for all non-negative integers.', 'The function handles negative input gracefully (e.g., raises an exception or returns an error code).', 'The function is efficient for reasonably sized inputs (iterative approach preferred for larger numbers).', 'The code is well-documented and easy to understand.', 'The function passes all unit tests.']}}\n",
            "❌ Solution Quality: 0.60 (Needs Improvement)\n",
            "\n",
            "=== Iteration 12 ===\n",
            "Problem: Create a simple text-based calculator that handles basic operations\n",
            "Task Analysis: {'task': 'Create a simple text-based calculator that handles basic operations', 'analysis': {'complexity': 3, 'required_skills': ['Basic programming knowledge', 'Understanding of input/output operations', 'Ability to handle user input', 'Familiarity with basic arithmetic operations (+, -, *, /)', 'Basic string manipulation (optional, for error handling)'], 'potential_challenges': ['Handling invalid input (e.g., non-numeric input)', 'Dealing with division by zero', 'Implementing error handling and user-friendly messages', 'Ensuring proper order of operations (PEMDAS/BODMAS)', 'Designing a clear and intuitive user interface'], 'recommended_approach': ['1. **Planning:** Define the scope (operations to be supported, input format, error handling).', '2. **Input:** Implement a method to get numerical input from the user (e.g., using `input()` in Python).', '3. **Operation Selection:** Get the operator (+, -, *, /) from the user.', '4. **Calculation:** Perform the calculation based on the selected operator.  Include error handling for invalid operators and division by zero.', '5. **Output:** Display the result to the user.', '6. **Error Handling:** Implement robust error handling to gracefully manage invalid input and potential exceptions (like division by zero).', '7. **Testing:** Test the calculator with various inputs, including edge cases and invalid data, to ensure correctness and robustness.', '8. **Iteration (Optional):** Add features like more advanced operations (e.g., exponents, modulo), memory functions, or a more sophisticated user interface.'], 'success_criteria': ['The calculator successfully performs basic arithmetic operations (+, -, *, /).', 'The calculator handles invalid input gracefully (e.g., displays an error message and prompts for re-entry).', 'The calculator prevents division by zero errors.', 'The calculator provides clear and understandable output.', \"The calculator's code is well-structured, readable, and maintainable.\"]}}\n",
            "❌ Solution Quality: 0.30 (Needs Improvement)\n",
            "\n",
            "=== Iteration 13 ===\n",
            "Problem: Design a system to find the shortest path between two points in a graph\n",
            "Task Analysis: {'task': 'Design a system to find the shortest path between two points in a graph', 'analysis': {'complexity': 6, 'requiredSkills': ['Graph theory fundamentals (nodes, edges, adjacency matrices/lists)', 'Algorithm design and analysis (time and space complexity)', 'Data structure selection and implementation (e.g., priority queues)', 'Programming skills in a suitable language (e.g., Python, Java, C++)', 'Software design principles (modular design, testability)', 'Testing and debugging skills'], 'potentialChallenges': ['Handling large graphs efficiently (memory and computation time)', 'Dealing with weighted graphs (different edge costs)', 'Managing different graph representations (adjacency matrix vs. adjacency list)', 'Handling negative edge weights (Bellman-Ford algorithm required)', 'Implementing efficient data structures for optimal performance', 'Ensuring correctness and robustness of the algorithm', 'Choosing the right algorithm for specific graph characteristics (sparse vs. dense)', 'Error handling (e.g., no path found)'], 'recommendedApproach': [{'step': 1, 'description': \"Choose an appropriate graph representation (adjacency matrix or adjacency list, considering the graph's density).\"}, {'step': 2, 'description': \"Select a suitable shortest path algorithm based on the graph characteristics and requirements (e.g., Dijkstra's algorithm for non-negative weights, Bellman-Ford for potentially negative weights, A* for heuristic optimization).\"}, {'step': 3, 'description': \"Implement the chosen algorithm efficiently using appropriate data structures (e.g., priority queues for Dijkstra's algorithm).\"}, {'step': 4, 'description': 'Thoroughly test the system with various test cases, including small, medium, and large graphs with different edge weights (including negative weights if the algorithm supports them) and topologies (cyclic, acyclic).'}, {'step': 5, 'description': 'Optimize the system for performance and memory usage, especially for large graphs.'}, {'step': 6, 'description': 'Document the design, implementation, and testing procedures.'}], 'successCriteria': ['The system correctly computes the shortest path between any two nodes in a graph.', 'The system handles different types of graphs (weighted/unweighted, directed/undirected).', 'The system handles large graphs efficiently in terms of time and space complexity.', 'The system is well-documented and easy to understand.', 'The system is thoroughly tested and robust.']}}\n",
            "❌ Solution Quality: 0.70 (Needs Improvement)\n",
            "\n",
            "=== Iteration 14 ===\n",
            "Problem: Implement a basic recommendation system for movies based on user preferences\n",
            "Task Analysis: {'task': 'Implement a basic movie recommendation system based on user preferences', 'analysis': {'complexity': 6, 'requiredSkills': ['Python programming', 'Data manipulation and cleaning (e.g., Pandas)', 'Basic understanding of machine learning algorithms (e.g., collaborative filtering, content-based filtering)', 'Data structures and algorithms', 'Working with datasets (e.g., CSV, JSON)', 'Model evaluation and selection', 'Basic understanding of database concepts (optional, depending on data storage)'], 'potentialChallenges': ['Data sparsity (limited user ratings for many movies)', 'Cold start problem (recommending movies for new users with limited history)', 'Data quality issues (incomplete or inconsistent data)', 'Scalability (handling large datasets and user base)', 'Choosing the right algorithm and hyperparameter tuning', 'Evaluating the effectiveness of the recommendation system (measuring precision, recall, etc.)'], 'recommendedApproach': [{'step': 1, 'description': 'Data Acquisition and Preprocessing: Gather movie data (titles, genres, etc.) and user ratings. Clean the data, handle missing values, and potentially create features like genre vectors or text embeddings.'}, {'step': 2, 'description': 'Algorithm Selection: Choose a suitable recommendation algorithm based on the data and desired complexity.  Start with a simpler approach like collaborative filtering (user-based or item-based) or content-based filtering. Consider hybrid approaches for better performance.'}, {'step': 3, 'description': \"Model Training and Evaluation: Train the chosen algorithm on the preprocessed data.  Split the data into training and testing sets to evaluate the performance using metrics like precision, recall, F1-score, or RMSE. Tune hyperparameters to optimize the model's performance.\"}, {'step': 4, 'description': 'System Implementation: Develop a basic interface (e.g., command-line or simple web interface) to interact with the system. Allow users to input their preferences and receive movie recommendations.'}, {'step': 5, 'description': 'Deployment and Monitoring: Deploy the system (if needed) and monitor its performance. Gather user feedback to further improve the system over time.'}], 'successCriteria': ['System successfully recommends movies based on user preferences.', 'Recommendation accuracy is acceptable (defined by appropriate evaluation metrics).', 'System is scalable to handle a reasonable number of users and movies.', 'System is user-friendly and easy to interact with.']}}\n",
            "❌ Solution Quality: 0.30 (Needs Improvement)\n",
            "\n",
            "=== Iteration 15 ===\n",
            "Problem: Create a machine learning model to predict house prices based on features\n",
            "Task Analysis: {'task': 'Create a machine learning model to predict house prices based on features', 'analysis': {'complexity': 7, 'required_skills': ['Data cleaning and preprocessing (handling missing values, outliers, feature scaling)', 'Feature engineering (creating new features from existing ones)', 'Exploratory data analysis (EDA) to understand data distributions and relationships', 'Model selection (choosing appropriate regression algorithms like Linear Regression, Random Forest, Gradient Boosting, etc.)', 'Model training and evaluation (using appropriate metrics like RMSE, MAE, R-squared)', 'Hyperparameter tuning (optimizing model parameters for better performance)', 'Model deployment (optional, depending on the project scope)', 'Programming skills (Python with libraries like Pandas, NumPy, Scikit-learn)', 'Understanding of machine learning concepts (regression, overfitting, underfitting)'], 'potential_challenges': ['Data quality issues (missing values, inconsistent data, outliers)', 'Feature selection (choosing the most relevant features)', 'High dimensionality of the data', 'Non-linear relationships between features and house prices', 'Overfitting the model to the training data', 'Handling imbalanced datasets (if applicable)', 'Interpreting model results and explaining predictions', 'Evaluating model performance on unseen data (generalization)'], 'recommended_approach': ['1. **Data acquisition and preprocessing:** Gather house price data, clean it, handle missing values, and perform feature scaling.', '2. **Exploratory data analysis (EDA):** Visualize the data, identify patterns, correlations, and outliers.', '3. **Feature engineering:** Create new features if necessary (e.g., combining features, creating interaction terms).', '4. **Model selection:** Choose appropriate regression algorithms (Linear Regression, Random Forest, Gradient Boosting, XGBoost, etc.) based on data characteristics and desired interpretability.', '5. **Model training and evaluation:** Split the data into training and testing sets, train the chosen model(s), and evaluate performance using metrics like RMSE, MAE, and R-squared.', '6. **Hyperparameter tuning:** Optimize model parameters using techniques like grid search or random search to improve performance.', '7. **Model selection and comparison:** Compare the performance of different models and select the best one based on evaluation metrics.', '8. **Model deployment (optional):** Deploy the model for making predictions on new data (e.g., creating a web application or API).'], 'success_criteria': ['Achieve a low RMSE (Root Mean Squared Error) and MAE (Mean Absolute Error) on the test set.', 'Obtain a high R-squared value, indicating a good fit of the model.', 'Demonstrate that the model generalizes well to unseen data.', 'Provide a clear and well-documented report detailing the data preprocessing, model selection, evaluation, and results.', 'Successfully deploy the model (if applicable).']}}\n",
            "❌ Solution Quality: 0.60 (Needs Improvement)\n",
            "\n",
            "🧠 Learning from experience...\n",
            "Learning error: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))\n",
            "\n",
            "📊 Cycle 3 Summary:\n",
            "  Average Solution Quality: 0.50\n",
            "  Current Capabilities: {'problem_solving': 0.4, 'code_generation': 0.6, 'learning_efficiency': 0.3, 'error_handling': 0.5}\n",
            "  Total Patterns Learned: 6\n",
            "\n",
            "\n",
            "        📈 AGENT PERFORMANCE REPORT\n",
            "        ========================================\n",
            "        \n",
            "        Total Iterations: 15\n",
            "        Average Solution Quality: 0.520\n",
            "        Average Solve Time: 7.20s\n",
            "        \n",
            "        Successful Solutions: 0\n",
            "        Failed Attempts: 15\n",
            "        Success Rate: 0.0%\n",
            "        \n",
            "        Current Capabilities:\n",
            "        {\n",
            "  \"problem_solving\": 0.4,\n",
            "  \"code_generation\": 0.6,\n",
            "  \"learning_efficiency\": 0.3,\n",
            "  \"error_handling\": 0.5\n",
            "}\n",
            "        \n",
            "        Patterns Learned: 6\n",
            "        Code Improvements: 2\n",
            "        \n",
            "\n",
            "==================================================\n",
            "TESTING IMPROVED AGENT\n",
            "==================================================\n",
            "\n",
            "=== Iteration 16 ===\n",
            "Problem: Create an efficient algorithm to sort a large dataset\n",
            "Task Analysis: {'task': 'Create an efficient algorithm to sort a large dataset', 'analysis': {'complexity': 7, 'requiredSkills': ['Algorithm design and analysis', 'Data structures (arrays, linked lists, heaps)', 'Big O notation', 'Space and time complexity analysis', 'Understanding of sorting algorithms (e.g., merge sort, quicksort, heapsort)', 'Software development skills (coding in a suitable language)', 'Testing and debugging skills', 'Performance optimization techniques'], 'potentialChallenges': ['Choosing the right algorithm for the dataset characteristics (size, type of data, pre-sortedness)', \"Handling memory constraints for extremely large datasets that don't fit in RAM\", 'Balancing time complexity with space complexity', 'Debugging and optimizing for performance bottlenecks', 'Dealing with different data types and comparison criteria', 'Ensuring algorithm stability (maintaining the relative order of equal elements)', 'Implementing parallel or distributed sorting for massive datasets'], 'recommendedApproach': {'step1': 'Analyze the dataset: Determine the size, data type, and any pre-existing order or characteristics.', 'step2': 'Select an appropriate sorting algorithm: Consider time and space complexity, stability requirements, and suitability for the data characteristics. For very large datasets, consider external sorting algorithms (e.g., merge sort based) or distributed sorting techniques.', 'step3': 'Implement the chosen algorithm: Use an efficient programming language and data structures.', 'step4': 'Test and optimize: Thoroughly test the algorithm with various datasets, analyze performance bottlenecks, and optimize for speed and memory usage.  Consider profiling tools.', 'step5': \"Evaluate and refine:  Measure the algorithm's performance (time and space) and refine it based on the evaluation. Consider alternative algorithms if performance is unsatisfactory.\"}, 'successCriteria': ['Algorithm correctly sorts the dataset.', 'Algorithm has acceptable time complexity (e.g., O(n log n) for comparison-based sorts).', 'Algorithm has acceptable space complexity.', 'Algorithm is robust and handles various edge cases.', 'Algorithm performs efficiently on large datasets.', 'Algorithm is well-documented and easy to understand.']}}\n",
            "❌ Solution Quality: 0.70 (Needs Improvement)\n",
            "\n",
            "Final Problem Solution Quality: 0.70\n"
          ]
        }
      ],
      "source": [
        "def setup_instructions():\n",
        "    \"\"\"Print setup instructions for Google Colab\"\"\"\n",
        "    instructions = \"\"\"\n",
        "    📋 SETUP INSTRUCTIONS FOR GOOGLE COLAB:\n",
        "\n",
        "    1. Install the Gemini API client:\n",
        "       !pip install google-generativeai\n",
        "\n",
        "    2. Get your Gemini API key:\n",
        "       - Go to https://makersuite.google.com/app/apikey\n",
        "       - Create a new API key\n",
        "       - Copy the key\n",
        "\n",
        "    3. Replace 'your-gemini-api-key-here' with your actual API key\n",
        "\n",
        "    4. Run the code!\n",
        "\n",
        "    🔧 CUSTOMIZATION OPTIONS:\n",
        "    - Modify test_problems list to add your own challenges\n",
        "    - Adjust improvement cycles count\n",
        "    - Add new capabilities to track\n",
        "    - Extend the learning mechanisms\n",
        "\n",
        "    💡 IMPROVEMENT IDEAS:\n",
        "    - Add persistent memory (save/load agent state)\n",
        "    - Implement more sophisticated evaluation metrics\n",
        "    - Add domain-specific problem types\n",
        "    - Create visualization of improvement over time\n",
        "    \"\"\"\n",
        "    print(instructions)\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    setup_instructions()\n",
        "    print(\"\\n\" + \"=\"*60)\n",
        "    main()"
      ]
    }
  ]
}